from django.core import validators
from django.db import models
from django.db.models import fields
from django.utils.html import escape
from django import forms
from django.contrib.sites.models import Site
from django.conf import settings

# Checking for settings or else using defaults
try:
    APPEND_SLASH = settings.SIMPLEPAGES_APPEND_SLASH
except AttributeError:
    APPEND_SLASH = True 
try:
    PREPEND_SLASH = settings.SIMPLEPAGES_PREPEND_SLASH
except AttributeError:
    PREPEND_SLASH = True
try:
    IMAGE_DIR = settings.SIMPLEPAGES_IMAGE_DIR
except AttributeError:
    IMAGE_DIR = 'images'
try:
    PREPOP_PAGE_URL = settings.SIMPLEPAGES_PREPOP_PAGE_URL
except AttributeError:
    PREPOP_PAGE_URL = True
try:
    HTML_EDITOR = settings.SIMPLEPAGES_HTML_EDITOR
except AttributeError:
    HTML_EDITOR = True



# Class for the HTML Text Area adds a class of "simple-html-editor" to the textarea to identify
# for the script to convert it. Otherwise it's a standard text field
class HTMLTextField(forms.TextField):
    def __init__(self, field_name, rows=15, cols=70, is_required=False, validator_list=[], maxlength=None):
        self.field_name = field_name
        self.rows, self.cols, self.is_required = rows, cols, is_required
        self.validator_list = validator_list[:]
        if maxlength:
            self.validator_list.append(self.isValidLength)
            self.maxlength = maxlength

    def render(self, data):
        if data is None:
            data = ''
        if isinstance(data, unicode):
            data = data.encode(settings.DEFAULT_CHARSET) 

        # adds a class to activate editor via editor_selector
        return '<textarea id="%s" class="v%s%s simple-html-editor" name="%s" rows="%s" cols="%s">%s</textarea>' % \
            (self.get_id(), self.__class__.__name__, self.is_required and ' required' or '',
            self.field_name, self.rows, self.cols, escape(data))

    def get_internal_type(self):
        return "TextField"


class HTMLField(fields.Field):
    def get_manipulator_field_objs(self):
        return [HTMLTextField]

    def get_internal_type(self):
        return "TextField"





class SiteSectionManager(models.Manager):
    def menu_items(self):
        return self.get_query_set().filter(show_in_nav__exact=True)

class SiteSection(models.Model):
    name = models.CharField(max_length=255)
    url = models.CharField(prepopulate_from=("name",), max_length=100, unique=True, blank=False)
    show_in_nav = models.BooleanField(default=True, db_index=True)
    order = models.PositiveIntegerField('Display Order', blank=True, null=True);
    
    class Admin:
        list_display = ('name', 'url', 'order', 'show_in_nav')
        search_fields = ('url', 'name')

    class Meta:
        ordering = ('order', 'name')

    def save(self):
        # If Enabled checking to ensure the urls start and end with
        # slashes
        if APPEND_SLASH:
            if self.url[-1] != '/':
                self.url = self.url + '/'
        if PREPEND_SLASH:
            if self.url[0] != '/':
                self.url = '/' + self.url 
        super(SiteSection, self).save() # Call the "real" save() method.

    def __unicode__(self):
        return u"%s" % (self.name)
    
    objects = SiteSectionManager()

class PageManager(models.Manager):
    def menu_items(self):
        return self.get_query_set().filter(show_in_nav__exact=True).order_by('order', 'nav_title')

class Page(models.Model):
    site_section = models.ForeignKey(SiteSection)
    url = models.CharField('URL', max_length=100, unique=True, validator_list=[validators.isAlphaNumericURL],
        help_text="Example: '/about-us/contact/'")
    title = models.CharField('Page Title', max_length=200)
    image = models.ImageField(upload_to=IMAGE_DIR, blank=True) #Media root is automatically prepended
    content = HTMLField(blank=True)
    show_in_nav = models.BooleanField(default=False, db_index=True,
        help_text="Check this box if this page should be shown in the primary navigation." )
    nav_title = models.CharField(max_length=150, blank=True,
        help_text="The link text that will show in the navigation menu")
    order = models.PositiveIntegerField(blank=True, null=True,
        help_text="The order this item should appear in the menu, defaults to alphabetical if order isn't specified");
    html_title = models.CharField(max_length=250, blank=True,
        help_text="This is the browser title")
    meta_description = models.TextField(blank=True)
    meta_keywords = models.TextField(blank=True)
    template_name = models.CharField('template name', max_length=70, blank=True,
        help_text="Example: 'pages/contact_page.html'. If this isn't provided, the system will use 'pages/default.html'.")
    registration_required = models.BooleanField('registration required', help_text="If this is checked, only logged-in users will be able to view the page.")

    class Meta:
        ordering = ('order', 'url',)

    class Admin:
        fields = (
            (None, {'fields': ('site_section', 'url', 'title', 'image', 'content')}),
            ('HTML Header Values', {'fields': ('html_title', 'meta_description', 'meta_keywords', ),'classes': 'collapse'}),
            ('Nav Menu Setup', {'fields': ('show_in_nav', 'nav_title', 'order'),'classes': 'collapse'}),
            ('Advanced options', {'classes': 'collapse', 'fields': ('registration_required', 'template_name')}),
        )
        list_display = ('url', 'title', 'order', 'site_section')
        list_filter = ('site_section',)
        search_fields = ('url', 'title')
        ordering = ('url', 'order')
        js = []
        if PREPOP_PAGE_URL:
            js.append('/simplepages/auto-url-prepend.js')
        if HTML_EDITOR:
            js.append("http://yui.yahooapis.com/2.5.1/build/yuiloader/yuiloader-beta-min.js")
            js.append('js/html_editor.js')

    def img_src(self):
        return settings.MEDIA_URL + self.image

    def save(self):
        # If Enabled checking to ensure the urls start and end with
        # slashes
        if APPEND_SLASH:
            if self.url[-1] != '/':
                self.url = self.url + '/'
        if PREPEND_SLASH:
            if self.url[0] != '/':
                self.url = '/' + self.url 
        super(Page, self).save() # Call the "real" save() method.

    def __unicode__(self):
        return u"%s -- %s" % (self.url, self.title)

    def get_absolute_url(self):
        return self.url

    objects = PageManager()

